<template>
  <div class="main_spac1" style="padding-bottom: 5px">
    <div class="main_white">
      <div class="main_crumbs boxdq">
        <div class="main_crumbs_l">
          <a href="javascript:;" @click="$router.back(-1)">
            <i class="el-icon-arrow-down"></i>返回
          </a>
          <em>|</em>
          <span>{{ title }}</span>
        </div>
      </div>
      <div class="main_tile boxdq marginTop10">
        <div class="main_tile_l"><em></em>基本信息</div>
      </div>
      <el-form
        :inline="true"
        :model="menuForm"
        class="demo-form-inline"
        ref="productFrom"
        label-width="100px"
        :rules="formRules"
        :disabled="!isEdit"
      >
        <el-form-item prop="name" label="菜谱名称：">
          <el-input class="wid180" v-model="menuForm.name" placeholder="菜谱名称" maxlength="10" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="用户分组：" prop="group_ids">
          <el-select
            v-model.trim="menuForm.group_ids"
            placeholder="请选择"
            class="wid180"
            filterable
            multiple
            collapse-tags
            clearable
            @change="handleIdsSelect"
          >
            <el-option
              v-for="statusList in userGroundList"
              :key="statusList.id"
              :label="statusList.title"
              :value="statusList.id"
              :disabled="statusList.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户：" prop="">
          <div @click="showAddUser">
            <el-input :value="('已选择' + disabledList.length + '个用户') || '选择用户' "></el-input>
          </div>
          <!-- <p @click="showAddUser" class="user-num" :class="{opacity: !disabledList.length}">{{ ('已选择' + disabledList.length + '个用户') || '选择用户' }}</p> -->
        </el-form-item>
        <el-form-item prop="remark" label="备注：">
          <el-input class="wid180" v-model="menuForm.remark" placeholder="备注"></el-input>
        </el-form-item>
        <div class="main_tile boxdq">
          <div class="main_tile_l"><em></em>菜谱清单</div>
        </div>
        <div class="change-time">
          <em>*</em>
          <el-date-picker
            v-model="times"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </div>
      </el-form>
      <AddDateMenu :dateTimes="times" ref="dateMenu" class="mg-l-10" :isEdit="isEdit"></AddDateMenu>
      <div class="mg-t-20 mg-l-10">
        <el-button type="primary" @click="save" v-if="isEdit">保 存</el-button>
        <el-button @click="cancel">取 消</el-button>
        <AddUser :selectGroup="menuForm.group_ids" @submit="userSubmit" :dialogShow="dialogShowUser" :options="userGroundList" :disabledList="disabledList" ref="addUser" @close="showAddUser"></AddUser>
      </div>
    </div>
  </div>
</template>

<script>
import { getInfo } from '@/api/menu.js'
import dayjs from 'dayjs'
import { addMenuData } from '../mockData'
import AddDateMenu from './components/AddDateMenu.vue'
import AddUser from './components/AddUser.vue'
const { menuForm, userGroundList, times } = addMenuData

export default {
  components: { AddDateMenu, AddUser },
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      dialogShow: false,
      rules: {
        num: [
          { required: true, message: "数量不能为空", trigger: "blur" },
          {
            pattern: /^(\d+\.?)?\d{0,2}$/,
            message: "请输入整数和两位小数",
            trigger: "blur"
          }
        ]
      },
      formRules: {
        name: [
          { required: true, message: "菜谱名称不能为空", trigger: "blur" }
        ],
        group_ids: [
          { required: true, message: "请选择用户分组", trigger: "change" }
        ]
      },
      menuForm,
      userGroundList,
      times,
      pickerOptions: {
        onPick: ({ maxDate, minDate }) => {
          // 如果选中的日期范围超过7天，则重置为7天
          if (maxDate && minDate && dayjs(maxDate).diff(minDate, 'day') > 6) {
            this.$message.error('最多可选择7天')
            // this.times = [dayjs(minDate).format('YYYY-MM-DD'), dayjs(minDate).add(6, 'day').format('YYYY-MM-DD')];
          }
        }
      },
      goodsId: '', //  新增页面没有id，编辑页面有id
      dialogShowUser: false,
      disabledList: [],
      isEdit: false,
      title: ''
    };
  },
  created() {
    getInfo('/common/getUserGroup', {}).then(res => {
      if(res.data) {
        this.userGroundList = res.data.map(el => {
          el.disabled = false
          el.id = el.id.toString()
          return el
        })  
      }
    })
    this.goodsId = this.$route.query.id || ''
    this.isEdit = eval(this.$route.query.isEdit)
    if(this.goodsId && this.goodsId) {
      this.getData(this.goodsId)
    }
    this.$route.meta.title = this.$route.query.id ? (this.isEdit ? '编辑菜谱' : '查看菜谱') : '新增菜谱'
    this.title = this.$route.meta.title
    if(this.$route.meta.title === '编辑菜谱') {
      getInfo('/packageMenu/check', {
        id: this.goodsId
      }, 'post').then(res => {
        this.isEdit = res.data.is_edit
        if(!res.data.is_edit) {
          this.$message.error(res.data.msg)
        }
      })
    }
  },
  methods: {
    getData(id) {
      getInfo('/packageMenu/info', {
        id: id
      }).then(res => {
        if(res.errcode == 0) {
          const { name, group_ids, user_ids, remark, date_range, packageMenuList  } = res.data
          this.menuForm.name = name
          this.menuForm.group_ids = group_ids.length ? group_ids : ['-1']
          this.menuForm.remark = remark
          this.times = date_range
          const listObj = {}
          this.disabledList = user_ids.map(el => {
            return {
              id: el
            }
          })
          packageMenuList.forEach(el => {
            listObj[el.send_at] = el.data.map((dataEl, index) => {
              if(dataEl.type === 'goods') {
                return {
                  ...dataEl,
                  price: Number(dataEl.market_price),
                  indexKey: new Date().getTime() + index,
                  name: dataEl.goods_name
                }
              }else {
                return {
                  ...dataEl,
                  indexKey: new Date().getTime() + index,
                  package_goods: (dataEl.package_goods || []).map((goodEl, goodIndex) => {
                    return {
                      ...goodEl,
                      price: Number(goodEl.market_price),
                      name: goodEl.goods_name,
                      indexKey: new Date().getTime() + goodIndex
                    }
                  })
                }
              }
            })
          })
          this.$nextTick(() => {
            this.$refs.dateMenu.changeList(listObj)
            
          })
        }
      })
    },
    saveGoods() {
      if(!this.name) {
        this.$message.error('请输入套餐名称！')
        this.$refs.nameInput.focus()
        return false
      }
      if(!this.imageList.length) {
        this.$message.error('请上传导入图片！')
        return false
      }
      if(!this.formData.tableList.length) {
        this.$message.error('请添加商品！')
        return false
      }else {
        if(!this.formData.tableList.every(el => el.num)) {
          this.$message.error('必填项不能为空！')
          return false
        }
      }
      const params = {
        status: this.isListing,
        name: this.name,
        goods_list: JSON.stringify(this.formData.tableList.map(el => {
          return {
            "goods_spu_id": el.goods_spu_id,
            "num": el.num,
            "unit": el.unit,
            id: el.id || '0'
          }
        })),
        img: this.imageList.map(el => el.path).join(",")
      }
      if(this.goodsId) params.id = this.goodsId
      let url = this.goodsId ? '/packageGoods/edit' : '/packageGoods/add'
      getInfo(url, params, 'post').then(res => {
        if(res.data) {
          const message = this.goodsId ? '修改套餐成功' : '新增套餐成功'
          this.$message.success(message)
          setTimeout(() => {
            this.name = ''
            this.imageList = []
            this.formData.tableList = []
            this.filelist = []
            this.$router.push('/menu/goods')
          }, 500)
        }
      })
    },
    cancel() {  //  取消
      this.$confirm("是否返回菜谱列表?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$router.push('/menu/list')
        })
        .catch(() => {});
    },
    save() {  //  保存
      this.$refs.productFrom.validate((val) => {
        if(val) {
          if(this.times.length) {
            let list = []
            let sendList = []
            if(this.$refs.dateMenu && this.$refs.dateMenu.containerList.length) {
              list = this.$refs.dateMenu.containerList
              sendList = list.map(el => {
                return {
                  send_at: el.send_at,
                  data: el.dataList.filter(item => item.name).map(dataItem => {
                    if(dataItem.type === 'goods') {
                      return {
                        type: dataItem.type,
                        goods_spu_id: dataItem.goods_spu_id,
                        num: dataItem.num
                      }
                    }else {
                      return {
                        type: dataItem.type,
                        package_goods_id: dataItem.package_goods_id,
                        package_goods: dataItem.package_goods.filter(item => item.num).map(packageItem => {
                          return {
                            goods_spu_id: packageItem.goods_spu_id,
                            num: packageItem.num
                          }
                        })
                      }
                    }
                  })
                }
              })
            }
            let bool = true
            sendList.forEach(el => {
              if(!el.data.length) bool = false
            })
            if(!bool) {
              this.$message.error('请新增套餐或商品！')
              return 
            }else {
              const params = {
                name: this.menuForm.name,
                remark: this.menuForm.remark,
                date_range: this.times.map(el => dayjs(el).format('YYYY-MM-DD')).join('_'),
                user_ids: this.disabledList.map(el => el.id).join(','),
                group_ids: this.menuForm.group_ids.join(','),
                goods_detail: JSON.stringify(sendList)
              }
              if(this.goodsId) params.id = this.goodsId
              const url = this.goodsId ? '/packageMenu/edit' : '/packageMenu/add'
              getInfo(url, params, 'post').then(res => {
                if(res.errcode == 0) {
                  const msg = this.$route.query.id ? '编辑菜谱成功' : '新增菜谱成功'
                  this.$message.success(msg)
                  this.$router.push('/menu/list')
                }else {
                  this.$message.success(res.errmsg)
                }
              }).catch(err => {
                this.$message.success(err)
              })
            }
          }else {
            this.$message.error('请选择时间！')
          }
        }
      })
    },
    showAddUser() {
      this.dialogShowUser = !this.dialogShowUser
      if(this.dialogShowUser) {
        this.$nextTick(() => {
          this.$refs.addUser.getData(this.menuForm.group_ids)
        })
      }
    },
    userSubmit(data) {
      this.disabledList = data
    },
    handleIdsSelect(val) {
      if(!val.length) {
        this.userGroundList.forEach(el => el.disabled = false)
      }else {
        if(val.includes('-1')) {
          this.userGroundList.forEach(el => el.disabled = !val.includes(el.id))
        }else {
          this.userGroundList.forEach(el => {
            if(el.id === '-1') el.disabled = true
          })
        }
      }
    }
  },
  beforeDestroy() {
    this.$refs.productFrom.resetFields()
    this.times = []
    this.disabledList = []
  }
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";
.el-range-editor--small.el-input__inner {
  width: 260px;
}
.main_white {
  padding: 10px 10px 10px 20px;
}
.mg-t-20 {
  margin-top: 20px;
}
.user-num {
  width: 180px;
  padding: 0 15px;
  border-radius: 4px;
  border: 1px solid #C0C4CC;
  &.opacity {
    opacity: .5;
  }
}
.change-time {
  margin-left: 10px;
  em {
    color: #F56C6C;
  }
}
.padding-right-0 {
  /deep/.el-form-item__label {
    padding-right: 0;
  }
}
/deep/.el-form-item {
  margin-bottom: 0px;
}

.main_upImg {
  float: left;
}
.maincp_spe {
  margin-left: 160px;
  margin-top: 10px;
  float: left;
  width: 81%;
  p {
    margin-right: 20px;
    font-size: $font_14;
    color: $colour_red;
    margin-bottom: 10px;
  }
}
.maincp_sp {
  p {
    margin-bottom: 10px;
    line-height: 22px;
    font-size: $font_14;
  }
}
.main_table {
  .image_gd {
    height: 120px;
  }
  .demo-image {
    position: relative;
    margin-left: 20px;
    border: 1px solid #f8f8f9;
    width: 120px;
    overflow: hidden;
    .el-upload-list__item-status-label {
      width: 40px;
      height: 24px;
      background: #13ce66;
      text-align: center;
      -webkit-transform: rotate(45deg);
      transform: rotate(45deg);
      -webkit-box-shadow: 0 0 1pc 1px rgba(0, 0, 0, 0.2);
      box-shadow: 0 0 1pc 1px rgba(0, 0, 0, 0.2);
      display: block;
      i {
        font-size: 12px;
        margin-top: 11px;
        color: $white;
        -webkit-transform: rotate(-45deg);
        transform: rotate(-45deg);
      }
    }
    &:first-child {
      margin-left: 0;
    }
    /deep/.el-image__inner {
      width: 120px;
      height: 120px;
    }
    img {
      width: 120px;
      height: 120px;
    }
  }
}
/deep/.el-upload--picture-card {
  position: inherit;
}
.detail-info {
  font-size: 14px;
  margin: 10px 0 7px 10px;
}
.mg-l-10 {
  margin-left: 10px;
}
.flex {
  display: flex;
  align-items: center;
}
.boxdq {
  justify-content: flex-start;
  .mg-l-34 {
    margin-left: 34px;
  }
}
/deep/.el-upload-list--picture-card .el-upload-list__item {
  width: 120px;
  height: 120px;

  &:first-child {
    margin-left: 0;
  }
}
/deep/.el-range-editor--small .el-range-separator {
  top: -1px;
}
</style>
